package com.zh.business.config.quartz;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;

/**
 * 描述: yml 配置
 * Job的创建是由Quartz通过反射创建的
 * 并未交由Spring容器创建。故原则上来说，是无法在Job实例中使用依赖注入
 * @author: yanglin
 * @Date: 2021-07-29-8:23
 * @Version: 1.0
 */
@Component
public final class JobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {

    private transient AutowireCapableBeanFactory autowireCapablebeanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        autowireCapablebeanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        // 使用AutowireCapableBeanFactory完成对IOC外Bean的注入操作
        autowireCapablebeanFactory.autowireBean(job);
        return job;
    }
}
